package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 *
 * @Title: woSyncPaymentResult
 * @Description:缴费状态回写API
 * @author: LiJuntao
 * @date 2021-07-13 23:58:55
 *
 */

public class woSyncPaymentResult implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(woSyncPaymentResult.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String dataSourceID = "dataSource";

        //接收客户端调用参数
        String callJson = "";
        String outData = "";

        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

       /* JSONObject signJson = signUtil.CheckSign(JSONObject.parseObject(callJson, Feature.OrderedField));
        log.info("[签名验证结果]:");
        log.info(signJson);
        if (signJson != null) {
            return signJson.toString();
        } else {
       */
            try {
                // 调用处理信息
                JSONObject inObject = JSONObject.parseObject(callJson, Feature.OrderedField);
                log.debug("处理前的Json：" + inObject.toString());

                String access_key = inObject.getString("access_key");
                String timestamp = inObject.getString("timestamp");
                String nonce = inObject.getString("nonce");
                String data = inObject.getString("data");

                log.debug("解析初始信息-access_key：" + access_key + " timestamp：" + timestamp + " nonce：" + nonce);

                outData = syncDataDeal(eliteBean, data, dataSourceID);

            } catch (Exception e) {
                log.error("接口处理异常" + e.getMessage());
                // 失败返回
                outData = "{\"code\":\"0\",\"msg\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

            }

            log.debug("缴费状态回写处理完成返回结果:" + outData);
            return outData;

       // }
    }

    // 数据接入处理
    public static String syncDataDeal(EliteBean eliteBean, String dataArr, String dataSourceID) {
        long startTime = System.currentTimeMillis();
        JSONArray arrJsonArray;
        Map<String, String> dealMap = new HashMap<String, String>();
        JSONArray resArray = new JSONArray();
        String reJson = null;
        try {
            arrJsonArray = JSONArray.parseArray(dataArr);

            int arrInt = arrJsonArray.size();
            log.debug("接入List数量:" + arrInt + " 数据内容:" + dataArr);

            for (int i = 0; i < arrInt; i++) {
                JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

                String payment_id = arrCustJson.getString("payment_id");
                String user_id = arrCustJson.getString("user_id");
                String payment_time = arrCustJson.getString("payment_time");
                String payment_amount = arrCustJson.getString("payment_amount");
                String payment_result = arrCustJson.getString("payment_result");
                String remark = arrCustJson.getString("remark");

                def updateSQL = "update dbc_payment_result set del_flag = 1 where payment_id = '" + payment_id + "'";
                eliteBean.update(updateSQL, dataSourceID);

                def InsertSQL = "INSERT INTO dbc_payment_result (rec_guid, payment_id, user_id, payment_time, payment_amount, payment_result, remark, sync_time, del_flag) VALUES" +
                        " (uuid(), '" + payment_id + "', '" + user_id + "', '" + payment_time + "', '" + payment_amount + "', '" + payment_result + "', '" + remark + "', now(), 0)";
                int row=eliteBean.update(InsertSQL, dataSourceID);

                String re_code;
                if(row>0){
				   re_code="1";
				}else{
				   re_code="0";
				}
                dealMap.put(payment_id, re_code);

            }

            // 将每条处理结果转换为JSONArray
            int j = 0;
            for (Map.Entry<String, String> m : dealMap.entrySet()) {
                JSONObject resObject = new JSONObject();
                resObject.put("payment_id", m.getKey());
                resObject.put("code", m.getValue());
                resArray.add(j, resObject);
                j++;
            }

            log.debug(resArray.toString());

            long endTime = System.currentTimeMillis();
            // 包装拼接返回JSONObject
            reJson = "{\"code\":\"1\",\"msg\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";

        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            reJson = "{\"code\":\"0\",\"msg\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
        }

        return reJson;
    }

}
